import demjson
import os
import urllib3
import sqlite3
import logging

logging.basicConfig(level=logging.INFO,format='%(asctime)s -%(levelname)s -%(process)d -%(module)s -%(funcName)s -%(message)s')
def getAnswerJson():
    http = urllib3.PoolManager()
    r = http.request(
        'GET',
        'http://xf.faxuan.net/ess/service/getpaper?paperId=2163&series=43_answer'
    )
    da = r.data
    da=da.decode("utf-8")
    das=da.split("\r\n")
    logging.info("read xhr data:%s"%(da))
    if(len(das) <3 ):
        logging.warning("xhr read error!")
        return None
    else:
        try:
            getjson = demjson.decode(das[2])
        except:
            logging.warning("json解析错误")
            return None
        else:
            return getjson

def sqlAnswerInsert(obj):
    if(obj== None):
        logging.warning("数据有误")
        return False
    db = sqlite3.connect(os.path.dirname(__file__) + "/test.db")
    cur = db.cursor()
    for d in obj:

        result=cur.execute("SELECT * FROM xf WHERE id= %s "%(d['questionId']))
        row=result.fetchone()
        if(row==None):
            cur.execute("INSERT INTO xf (id,answerNo) VALUES (%s,'%s')"%(d['questionId'],d['answerNo']))
            db.commit()
            logging.info("INSERT id:%s ; answerNo:%s"%(d['questionId'],d['answerNo']))
        elif (row[4]=="" or row[4]==None):
            cur.execute("UPDATE xf SET answerNo='%s' WHERE (id=%s)" % (d['answerNo'],d['questionId']))
            db.commit()
            logging.info("UPDATE id:%s ; answerNo:%s" % (d['questionId'], d['answerNo']))
        elif(row[4] != d['answerNo'] ):
            logging.error("answerNo conflict!")
    db.close()


obj=getAnswerJson()
sqlAnswerInsert(obj)
